//
//  MTCContractProjectViewController.m
//  ERP
//
//  Created by QA on 15/9/22.
//  Copyright (c) 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MTCContractProjectViewController.h"
#import "MJRefresh.h"
#import "MTCContractProjectViewCell.h"
#import "UITableView+Custom.h"

#import "WebServiceCommonRequest.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "MTCProjectDetailViewController.h"
#import "MTCCreateProjectViewController.h"

@interface MTCContractProjectViewController ()

@property (strong, nonatomic) NSDictionary *concreteInfo;
@property (strong, nonatomic) NSMutableArray *resultData;

@end

@implementation MTCContractProjectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"合同工程"];
        NSArray *mainMenuArray1 = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTGC_CZ"];
        if (mainMenuArray1.count>0){
            UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStyleDone target:self action:@selector(addConcreteProjectSelector:)];
            self.navigationItem.rightBarButtonItem = leftButton;
        }
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getPassingParameter:(id)object
{
    if (!object) return;
    if ([object isKindOfClass:[NSDictionary class]])
        self.concreteInfo = object;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self.tableView registerClass:[MTCContractProjectViewCell class] forCellReuseIdentifier:@"MTCContractProjectViewCell"];
    [self setupRefresh];
    
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
}

- (void)addConcreteProjectSelector:(id)selector
{
    NSArray *valueArray = @[self.concreteInfo];
    
    MTCCreateProjectViewController *view = [[MTCCreateProjectViewController alloc] initWithValue:valueArray];
    view.backResultDelagate = self;
    view.key = @"CreateProject";
    [self.navigationController pushViewController:view animated:YES];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self getNetWorkData];
}

#pragma mark 网络获取数据

- (void)getNetWorkData
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_GCMC_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    NSString *concreteID = [self.concreteInfo objectFormatStringForKey:@"合同ID"];
    [content addParameterKey:@"合同ID" value:concreteID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView headerEndRefreshing];
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无工程" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MTCContractProjectViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MTCContractProjectViewCell"];
    
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
    cell.GCMCLabel.text = [itemData objectFormatStringForKey:@"工程名称" defaults:@"无工程名称"];
    cell.GCDZLabel.text = [itemData objectFormatStringForKey:@"工地地址" defaults:@"未录入"];
    cell.SGDWRLabel.text = [itemData objectFormatStringForKey:@"施工单位" defaults:@"未录入"];
    cell.JSDWLabel.text = [itemData objectFormatStringForKey:@"建设单位" defaults:@"未录入"];
    cell.YSJLLabel.text = [itemData objectFormatStringForKey:@"运输距离" defaults:@"未录入"];
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 86;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
    
    NSArray *array = @[self.concreteInfo,itemData];
    MTCProjectDetailViewController *viewController = [[MTCProjectDetailViewController alloc] initWithValue:array];
    viewController.backResultDelagate = self;
    viewController.key = @"ModifProject";
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if (!backValue) return;
    
    //新增工程
    if ([key isEqualToString:@"CreateProject"]) {
        NSDictionary *valueDic = backValue;
        [self.resultData insertObject:valueDic atIndex:0];
        [self.tableView reloadData];
        
        if(self.resultData && self.resultData.count > 0)
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        
    } else if ([key isEqualToString:@"ModifProject"]) {
        //修改工程
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        [self.resultData removeObjectAtIndex:index];
        [self.resultData insertObject:originalArray[1] atIndex:index];
        [self.tableView reloadData];
    }
}

@end
